﻿using System.Collections.Concurrent;
using System.IO;
using Volo.Abp.DependencyInjection;

namespace FlyingEye.Common.Utils
{
    /// <summary>
    /// 线程安全的文本读取器
    /// </summary>
    public class ConcurrentTextReader : ITransientDependency
    {
        private readonly ConcurrentDictionary<string, object> _fileLocks = new ConcurrentDictionary<string, object>();

        public string ReadAllText(string filePath)
        {
            string fullPath = GetFullPath(filePath);
            object fileLock = GetFileLock(fullPath);

            lock (fileLock)
            {
                string fileContent = File.ReadAllText(fullPath);
                return fileContent;
            }
        }

        public byte[] ReadAllBytes(string filePath)
        {
            string fullPath = GetFullPath(filePath);
            object fileLock = GetFileLock(fullPath);

            lock (fileLock)
            {
                byte[] fileBytes = File.ReadAllBytes(fullPath);
                return fileBytes;
            }
        }

        private string GetFullPath(string filePath)
        {
            return Path.GetFullPath(filePath);
        }

        private object GetFileLock(string filePath)
        {
            return _fileLocks.GetOrAdd(filePath, new object());
        }

        private void RemoveFileLock(string filePath)
        {
            _fileLocks.TryRemove(filePath, out _);
        }
    }
}
